import { Component, EventEmitter, Input, NgZone, OnInit, Output } from '@angular/core';
import { HttpService } from "../../../http/http.service";
import { NotifyService } from "../../../utils/notify.service";

@Component({
  selector: 'meta-treetable',
  templateUrl: './meta-treetable.component.html',
  styleUrls: ['./meta-treetable.component.styl']
})
export class MetaTreetableComponent implements OnInit {

  constructor(private http: HttpService, private zone: NgZone, private notify: NotifyService) {
  }

  ngOnInit() {
    this.onSearch();
  }

  @Input() parent: string = null;                      // 调用源，主要用于定制开发
  @Input() url: string;                                // 查询URL
  @Input() searchForm = {};                            // 查询条件
  @Input() columns = [];                               // 表格列信息
  @Input() lineBtnGroup = [];                          // 行操作按钮
  @Input() lineBtnWidth: number = 100;                 // 行操作按钮宽度
  @Output() lineBtnClick = new EventEmitter<object>(); // 行操作按钮点击
  @Output() lineClick = new EventEmitter<object>();    // 行点击
  @Input() lineClickColor = '';                        // 行点击的背景色
  lineClickRow = null;                                 // 点击的行

  total = 0;
  treeData: any[] = [];
  mapOfExpandedData: { [id: string]: any[] } = {};
  colorOfExpandedData: { [id: string]: string } = {};  // 用于保存各行的背景色

  collapse(array: any[], data: any, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.id === d.id)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: any): any[] {
    const stack: any[] = [];
    const array: any[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: true });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: true, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: any, hashMap: { [id: string]: boolean }, array: any[]): void {
    if (!hashMap[node.id]) {
      hashMap[node.id] = true;
      array.push(node);
    }
  }

  getData() {
    return this.treeData;
  }

  setData(data) {
    this.treeData = data;
    this.setExpandedData();
  }

  getExpandedData() {
    let list = [];
    for (let id in this.mapOfExpandedData) {
      let subList = this.mapOfExpandedData[id];
      subList.forEach(item=>{
        list.push(item);
      })
    }

    return list;
  }

  setExpandedData() {
    this.treeData.forEach(item => {
      this.mapOfExpandedData[item.id] = this.convertTreeToList(item);
    });
  }

  onSearch(): void {
    if (!this.url) {
      return;
    }

    let para = {
      params: encodeURI(JSON.stringify(this.searchForm))
    };

    this.http.get(this.url, para).subscribe(res => {
      if (res.err == '0') {
        this.treeData = res.data;
        this.setExpandedData();
        this.total = res.recordCount;
      } else {
        this.notify.error(res.errMsg).subscribe();
      }
    });
  }

  /**
   * 行操作按钮点击
   * @param btnId 按钮ID
   * @param rowData 行数据
   */
  onLineBtnClick(btn, rowData: any): void {
    if (btn.click) {
      btn.click(rowData);
    } else {
      this.lineBtnClick.emit({ 'btnId': btn.id, 'rowData': rowData });
    }
  }

  onRowClick(rowData: any): void {
    this.lineClickRow = rowData;

    // 设置行背景色
    for (let id in this.colorOfExpandedData) {
        // 非点击的行
        this.colorOfExpandedData[id] = '';
    }
    // 点击的行
    this.colorOfExpandedData[rowData.id] = this.lineClickColor;

    this.lineClick.emit({ 'rowData': rowData });
  }

}
